/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/serialize-and-deserialize-binary-tree
   @Language: C++
   @Datetime: 16-02-09 05:43
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
	/**
	 * This method will be invoked first, you should design your own algorithm 
	 * to serialize a binary tree which denote by a root node to a string which
	 * can be easily deserialized by your own "deserialize" method later.
	 */
	string serialize(TreeNode * root) {
		// write your code here
		if(root==NULL) return "";
		string res;
		queue<TreeNode*> que;
		char str[32];
		for(que.push(root); que.size(); que.pop()){
			TreeNode *node=que.front();
			if(node) {
				sprintf(str,"%d ",node->val);
				res.append(str);
				que.push(node->left);
				que.push(node->right);
			}
			else res.append("# ");
		}
		return res;
	}

	/**
	 * This method will be invoked second, the argument data is what exactly
	 * you serialized at method "serialize", that means the data is not given by
	 * system, it's given by your own serialize method. So the format of data is
	 * designed by yourself, and deserialize it here as you serialize it in 
	 * "serialize" method.
	 */
	TreeNode * deserialize(string &data) {
		// write your code here
		if(data.length()<1) return NULL;
		stringstream iostr(data);
		queue<TreeNode*> que;
		char str[32];
		iostr>>str;
		TreeNode *root=new TreeNode(atoi(str)), *node;
		for(que.push(root); que.size(); que.pop()){
			node=que.front();
			iostr>>str;
			if(str[0]!='#'){
				node->left=new TreeNode(atoi(str));
				que.push(node->left);
			}
			iostr>>str;
			if(str[0]!='#'){
				node->right=new TreeNode(atoi(str));
				que.push(node->right);
			}
		}
		return root;
	}
};
